package com.geyue.controller;

import com.geyue.common.toolbox.result.Res;
import com.geyue.core.model.Product;
import com.geyue.core.model.ProductProp;
import com.geyue.core.service.ProductPropService;
import com.geyue.core.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by Lyon on 2017/5/16.
 */
@Controller
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;
    @Autowired
    private ProductPropService propService;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String list() {
        return "product/list";
    }

    @RequestMapping(value = "/", method = RequestMethod.POST)
    @ResponseBody
    public Res list(Product product, Integer pageSize, Integer pageNum) {
        return Res.success("", productService.getPage(pageNum, pageSize, product));
    }

    @RequestMapping(value = "/", method = RequestMethod.PUT)
    @ResponseBody
    public Res put(Product product) {

        if (productService.updateNotEmpty(product) > 0)
            return Res.success("修改成功!");

        return Res.fail("修改失败!");
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public Res put(@PathVariable Integer id) {

        if (productService.deleteByKey(id) > 0){
            ProductProp prop = new ProductProp();
            prop.setPid(id);
            if(propService.delete(prop) > 0)
                return Res.success("删除成功!");
        }

        return Res.fail("删除失败!");
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add() {
        return "product/add";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Res add(Product product) {

        if (productService.saveNotEmpty(product) > 0)
            return Res.success("添加成功!");

        return Res.fail("添加失败!");
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String list(@PathVariable Integer id, Model model) {

        model.addAttribute("userInfo", productService.getOneByKey(id));
        return "product/edit";
    }



}
